﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace AUV5.Common
{
    public static class FileHelper
    {
        #region  目录操作 by amos

        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="path"></param>
        public static System.IO.DirectoryInfo CreatDirectory(string path)
        {
            System.IO.DirectoryInfo dInfo = null;

            try
            {
                if (!System.IO.Directory.Exists(path))
                {
                    dInfo = System.IO.Directory.CreateDirectory(path);
                }
            }
            catch (Exception)
            {
                throw;
            }

            return dInfo;
        }

        /// <summary>
        /// 得到目录下所有文件
        /// </summary>
        /// <param name="dirPath"></param>
        /// <returns></returns>
        public static System.IO.FileInfo[] GetFiles(string dirPath)
        {
            try
            {
                System.IO.FileInfo[] files = new System.IO.FileInfo[0];
                System.IO.DirectoryInfo dInfo = null;

                if (System.IO.Directory.Exists(dirPath))
                {
                    dInfo = new System.IO.DirectoryInfo(dirPath);
                    files = dInfo.GetFiles();
                }

                return files;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 移除目录
        /// </summary>
        /// <param name="path">要移除的空目录的名称，此目录必须为可写或为空</param>
        public static void DeleteDirectory(string path)
        {
            try
            {
                if (System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.Delete(path);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 移除目录
        /// </summary>
        /// <param name="path">要移除的目录的名称</param>
        /// <param name="recursive">若要移除 DirectoryName 目录中的目录、子目录、文件，则为true，否则为false。</param>
        public static void DeleteDirectory(string path, bool recursive)
        {
            try
            {
                if (System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.Delete(path, recursive);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion

        #region 文件操作 by amos

        /// <summary>
        /// 复制文件 
        /// </summary>
        /// <param name="previewpath"></param>
        public static void Copy(string sourcefile,string destpath)
        {
            try
            {
                string source = HttpContext.Current.Server.MapPath(sourcefile);
                string dest = HttpContext.Current.Server.MapPath(destpath);
                if (File.Exists(source))
                {
                    File.Copy(source, dest);
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        /// <summary>
        /// 移除文件
        /// </summary>
        /// <param name="filePath">要删除的文件路径</param>
        public static void DeleteFile(string filePath)
        {
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 移除目录下同级的所有文件
        /// </summary>
        /// <param name="path">要移除的目录的名称</param>
        public static void DeleteDirectoryFiles(string path)
        {
            try
            {
                if (System.IO.Directory.Exists(path))
                {
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
                    System.IO.FileInfo[] files = dir.GetFiles();

                    for (int i = 0; i < files.Length; i++)
                    {
                        DeleteFile(files[i].FullName);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 移除目录下的所有文件以及所有子目录的文件
        /// </summary>
        /// <param name="path">要移除的目录的名称</param>
        public static void DeleteDirectoryAllFiles(string path)
        {
            try
            {
                if (System.IO.Directory.Exists(path))
                {
                    DeleteDirectoryFiles(path);

                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);

                    System.IO.DirectoryInfo[] dirs = dir.GetDirectories();

                    for (int i = 0; i < dirs.Length; i++)
                    {
                        DeleteDirectoryAllFiles(dirs[i].FullName);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion



        /// <summary>
        /// 获取唯一的文件名（时间+随机数+扩展名）
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        public static string GetUniqueFileName()
        {
            return string.Format("{0}{1}", DateTime.Now.ToString("yyyyMMddHHmmssffff"), new Random().Next(1000,9999));
        }


        /// <summary>
        /// 缩放图片（将较小的一边设为目标值，较大的边按比例缩小）
        /// </summary>
        /// <param name="filepath">长和宽都必须大于目标值</param>
        /// <param name="height"></param>
        /// <param name="width"></param>
        /// <param name="destpath"></param>
        /// <returns></returns>
        public static void MakeScaleMap(string filepath, int height, int width, string destpath)
        {
            Image img = null;
            Image destimg = null;
            try
            {
                img = Image.FromFile(filepath);
                int h = img.Height;
                int w = img.Width;

                int destheight = 0;
                int destwidth = 0;
                if (h >= height && w >= width)
                {
                    //如果原图的长/宽比例大于目标的长/宽比例
                    if (((double)h / (double)w)==((double)height / (double)width))
                    {
                        destwidth = width;
                        destheight = height;
                    }
                    else if (((double)h / (double)w) > ((double)height / (double)width))
                    {
                        destheight = Convert.ToInt32(Convert.ToDouble(width) / Convert.ToDouble(w) * h);   //得到缩放后的高
                        destwidth = width;
                    }
                    else
                    {
                        destheight = height;
                        destwidth = Convert.ToInt32(Convert.ToDouble(height) / Convert.ToDouble(h) * w);  //得到缩放后的宽           
                    }
                    destimg = FileHelper.GetThumbNailImage(img, destwidth, destheight);
                    destimg.Save(destpath);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (destimg != null)
                {
                    destimg.Dispose();
                }                
            }

        }
        /// <summary>
        /// 按固定的尺寸切图（切中间的部分）
        /// </summary>
        /// <param name="img"></param>
        /// <param name="height"></param>
        /// <param name="width"></param>
        /// <param name="destpath"></param>
        public static void CutImage(string filepath, int height, int width, string destpath)
        {
            Image img = null;
            Bitmap bitmap=null;
            Graphics gra = null;
             
            try
            {
                img = Image.FromFile(filepath);
                bitmap = new Bitmap(width, height);
                gra = Graphics.FromImage(bitmap);
                int x = 0;
                int y = 0;
                int w = img.Width;
                int h = img.Height;
                if (h > w)
                {
                    y = (h - w) / 2;
                }
                else
                {
                    x = (w - h) / 2;
                }
                Rectangle rec = new Rectangle(x, y, width, height);
                gra.DrawImage(img, 0, 0, rec, GraphicsUnit.Pixel);
                bitmap.Save(destpath);
            }
            catch
            {

                throw;
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (img != null)
                {
                    gra.Dispose();
                }               
            }

        }
        /// <summary>
        /// 获取一个图片按等比例缩小后的大小。
        /// </summary>
        /// <param name="maxWidth">需要缩小到的宽度</param>
        /// <param name="maxHeight">需要缩小到的高度</param>
        /// <param name="imageOriginalWidth">图片的原始宽度</param>
        /// <param name="imageOriginalHeight">图片的原始高度</param>
        /// <returns>返回图片按等比例缩小后的实际大小</returns>
        private static Size GetNewSize(int maxWidth, int maxHeight, int imageOriginalWidth, int imageOriginalHeight)
        {
            double w = 0.0; 
            double h = 0.0;
            double sw = Convert.ToDouble(imageOriginalWidth);
            double sh = Convert.ToDouble(imageOriginalHeight);
            double mw = Convert.ToDouble(maxWidth);
            double mh = Convert.ToDouble(maxHeight);

            if (sw < mw && sh < mh)
            {
                w = sw;
                h = sh;
            }
            else if ((sw / sh) > (mw / mh))
            {
                w = maxWidth;
                h = (w * sh) / sw;
            }
            else
            {
                h = maxHeight;
                w = (h * sw) / sh;
            }

            return new Size(Convert.ToInt32(w), Convert.ToInt32(h));
        }

        /// <summary>
        /// 对给定的一个图片（Image对象）生成一个指定大小的缩略图。
        /// </summary>
        /// <param name="originalImage">原始图片</param>
        /// <param name="thumMaxWidth">缩略图的宽度</param>
        /// <param name="thumMaxHeight">缩略图的高度</param>
        /// <returns>返回缩略图的Image对象</returns>
        public static System.Drawing.Image GetThumbNailImage(System.Drawing.Image originalImage, int thumMaxWidth, int thumMaxHeight)
        {
            Size thumRealSize = Size.Empty;
            Image newImage = originalImage;
            Graphics graphics = null;

            try
            {
                thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height);
                newImage = new Bitmap(thumRealSize.Width, thumRealSize.Height);
                graphics = Graphics.FromImage(newImage);

                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;

                graphics.Clear(Color.Transparent);

                graphics.DrawImage(originalImage, new Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new Rectangle(0, 0, originalImage.Width, originalImage.Height), GraphicsUnit.Pixel);
            }
            catch { }
            finally
            {
                if (graphics != null)
                {
                    graphics.Dispose();
                }
            }

            return newImage;
        }

        /// <summary>
        /// 对给定的一个图片文件生成一个指定大小的缩略图。
        /// </summary>
        /// <param name="originalImage">图片的物理文件地址</param>
        /// <param name="thumMaxWidth">缩略图的宽度</param>
        /// <param name="thumMaxHeight">缩略图的高度</param>
        /// <returns>返回缩略图的Image对象</returns>
        private static System.Drawing.Image GetThumbNailImage(string imageFile, int thumMaxWidth, int thumMaxHeight)
        {
            System.Drawing.Image originalImage = null;
            System.Drawing.Image newImage = null;

            try
            {
                originalImage = System.Drawing.Image.FromFile(imageFile);
                newImage = GetThumbNailImage(originalImage, thumMaxWidth, thumMaxHeight);
            }
            catch { }
            finally
            {
                if (originalImage != null)
                {
                    originalImage.Dispose();
                }
            }

            return newImage;
        }

        /// <summary>
        /// 对给定的一个图片文件生成一个指定大小的缩略图，并将缩略图保存到指定位置。
        /// </summary>
        /// <param name="sourcePath">图片的物理文件地址</param>
        /// <param name="destPath">缩略图的物理文件地址</param>
        /// <param name="width">缩略图的宽度</param>
        /// <param name="height">缩略图的高度</param>
        public static void MakeThumbNail(string sourcePath, string destPath, int width, int height)
        {
            System.Drawing.Image newImage = GetThumbNailImage(sourcePath, width, height);
            try
            {
                newImage.Save(destPath, ImageFormat.Jpeg);
            }
            catch
            { }
            finally
            {
                newImage.Dispose();
            }
        }


       
    }

}